#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<cstring>

void Usge(std::string s)
{
  std::cout<<s<<" "<< "ip port"<<std::endl;
}


int main(int argc,char* argv[])
{
  if(argc != 3)
  {
    Usge(argv[0]);
    return 1;
  }
  
  //create socket
  int sock= socket(AF_INET,SOCK_STREAM,0);
  if(sock < 0)
  {
    std::cout<<"socket fail"<<std::endl;
    return 1;
  }
  u_int16_t port = atoi(argv[2]);
  

  std::string ip = argv[1];
  //bind 不需要显示绑定
  
  //set server  
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(port);
  server.sin_addr.s_addr = inet_addr(ip.c_str());
  
  //connet
  if(connect(sock,(struct sockaddr*)&server,sizeof(server))< 0)
  {
    std::cout<<"connect fail"<<std::endl;
    return 2;
  }

  std::cout<<"connect succeed"<<std::endl;
  
  //send service
  while(true)
  {
    char buffer[1024] = {0};
    std::cout<<"Please Enter #";
    
    fgets(buffer,sizeof(buffer)-1,stdin);
    
    //write
    write(sock,buffer,strlen(buffer));
    
    ssize_t s = read(sock,buffer,sizeof(buffer)-1);
 
    if(s > 0)
    {
      buffer[s] = 0;
      std::cout<<"server # "<<buffer<<std::endl;
    }
    else if(s == 0)
    {
      std::cout<<"server quit"<<std::endl;
      return 5;
    }
    else 
    {
      std::cout<<"read erreo"<<std::endl;
      break;
    }
  }
}
